package main

import (
	"os"

	"gitee.com/Luna-CY/Golang-Project-Template/internal/configuration"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/configuration/loader"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/i18n"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/runtime"
	"github.com/getsentry/sentry-go"
	"github.com/spf13/cobra"
)

func NewWorkerCommand() *cobra.Command {
	var config string

	var command = &cobra.Command{
		Use:  "worker",
		Args: cobra.NoArgs,
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			// 先加载本地配置文件
			if err := loader.LoadConfigFromFile(config, &configuration.Configuration); nil != err {
				cmd.PrintErrf("error loading config: %v\n", err)

				os.Exit(1)
			}

			// 初始化日志，初始化日志时依赖配置参数
			logger.Init()

			// 加载数据库配置，数据库查询依赖日志配置
			if err := loader.LoadConfigFromDb(&configuration.Configuration); nil != err {
				cmd.PrintErrf("error loading config from db: %v\n", err)

				os.Exit(1)
			}

			// 启动配置自动加载，依赖日志配置
			loader.StartAutoLoader(&configuration.Configuration)

			// 初始化国际化
			if err := i18n.Init(); nil != err {
				cmd.PrintErrf("Error init i18n: %v\n", err)
			}

			// 初始化sentry
			if configuration.Configuration.Sentry.Enable && "" != configuration.Configuration.Sentry.Dsn {
				hostname, _ := os.Hostname()

				option := sentry.ClientOptions{
					Release:          runtime.Release,
					AttachStacktrace: true,
					Debug:            configuration.Configuration.Debug,
					ServerName:       hostname,
					Environment:      runtime.GetEnvironment(),
					Dsn:              configuration.Configuration.Sentry.Dsn,
				}

				if err := sentry.Init(option); err != nil {
					cmd.PrintErrf("Error init sentry: %v\n", err)

					os.Exit(1)
				}
			}

			// Perform any necessary setup or initialization here
		},
	}

	command.PersistentFlags().StringVarP(&config, "config", "c", "config", "config dir path (default is config)")

	command.AddCommand(NewWorkerClearObjectCommand(), NewWorkerSendEmailCommand(), NewWorkerSendSmsCommand())

	return command
}
